import allure
import cv2
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.webdriver import WebDriver
from selenium.common import NoSuchElementException


class Base:
    _IMPLICITLY = 20

    def __init__(self, driver: WebDriver = None):
        self.driver = driver

    def find(self, by, locator=None):
        """找到元素并返回元素"""
        if locator == None:
            element = self.driver.find_element(*by)
        else:
            element = self.driver.find_element(by, locator)
        imgpath = self.draw_rectangle_in_screenshot(element)
        allure.attach.file(imgpath, name="页面截图", attachment_type=allure.attachment_type.PNG)
        return element

    def find_click(self, by, locator=None):
        """找到元素并完成点击操作"""
        self.find(by, locator).click()

    def find_and_send(self, text, by, locator=None):
        """找到元素并完成输入操作"""
        self.find(by, locator).send_keys(text)

    def get_toast_text(self):
        """ 获取 toast 文本"""
        return self.driver.find_element(AppiumBy.XPATH, "//*[@class='android.widget.Toast']").text

    def swipe_find(self, text, max_num=3):
        """滑动查找"""
        # max_num = 3
        self.set_implicit(1)
        for i in range(max_num):
            try:
                # 每次找元素都要等足 _IMPLICITLY 隐式等待时长
                element = self.driver.find_element(AppiumBy.XPATH, f"//*[@text='{text}']")
                self.set_implicit(self._IMPLICITLY)
                return element
            except NoSuchElementException:
                # 滑动
                size = self.driver.get_window_size()
                # 'width', 'height'
                startx = size.get("width") / 2
                starty = size.get("height") * 0.8

                endx = startx
                endy = size.get("height") * 0.3
                duration = 500
                # 滑动
                self.driver.swipe(startx, starty, endx, endy, duration)
            if i == max_num - 1:
                # 找了最大次数 ，仍然未找到
                self.set_implicit(self._IMPLICITLY)
                raise NoSuchElementException(f"找了 {max_num} 次，未找到 {text}")

    def set_implicit(self, waittime):
        self.driver.implicitly_wait(waittime)

    def screenshot(self, imgpath):
        self.driver.save_screenshot(imgpath)

    def draw_rectangle_in_screenshot(self, element, color_rgb=(255, 0, 0)):
        '''在图上上画矩形
        start_point: 起点的坐标，tuple 类型，例如：(100, 100)
        end_point: 终点的坐标，tuple 类型，例如：(200, 200)
        color_rgb: 画线对应的rgb颜色 例如：(0, 255, 0)
        '''
        start_x = element.location.get("x")
        start_y = element.location.get("y")
        end_x = element.size.get("width") + start_x
        end_y = element.size.get("height") + start_y
        start_point = (start_x, start_y)
        end_point = (end_x, end_y)
        img_path = "tmp.png"
        self.screenshot(img_path)

        # 读取图片
        image = cv2.imread(img_path)
        # 画矩形
        cv2.rectangle(image, start_point, end_point, color_rgb, 5)
        # 写到文件中
        cv2.imwrite(img_path, image)
        return img_path
